let app = getApp();
import {
  getPersonAuth,
  realPersonAuth,
  checkPersonAuth,
  createPreAuth,
  createContract,
  createHuabei,
  createAntchain
} from "../../api/index";
import { uploadImg } from "../../utils/request";
import { checkName, validateIdCard } from "../../utils/validate";
import { disposeData, backMini } from "../../utils/outData";
const esignPlugin = requirePlugin("esign");
Page({
  data: {
    userName: '',
    userIdcard: '',
    card_front: '',
    card_back: '',
    frontCard: [],
    backCard: [],
    orderId: '',
    payType: '',
    contractType: '',  //合同类型  1蚂蚁智能合同  2E签宝合同
    // signNum: '',       //签署方数量   2两方  3三方
    isReady: false,
    isAuth: '',
    orderStatus: '',
    esignFlowId: '',
    esignUserId: '',
    cradName:'',
    cradId:'',
    gooddsId:'',
    setmealId:'',
    spectId:'',
    amount:'',
    activityId:'',
    authStatus:'',
    checkAuth:'',
    flag:'',
    type:''
  },
  onLoad(option) {
    my.removeStorage({ key: 'hasCreateSign' });
    my.removeStorage({ key: 'authStatus' });
    const { orderId, payType, esignUserId, flowId, isAuth, status, contractType } = option
    this.setData({
      orderId,
      payType,
      isAuth,
      orderStatus: status,
      esignFlowId: flowId,
      esignUserId,
      contractType,
      cradId:option.cradId,
      cradName:option.cradName,
      gooddsId:option.goodsId,
      setmealId:option.setmealId,
      spectId:option.specId,
      amount:option.amount,
      activityId:option.activityId,
      flag:option.beforeAuth
    })
    console.log(option);
    getPersonAuth().then(res => {
      this.setData({
        userName: res.certName,
        userIdcard: res.certNo,
        card_front: res.cardFront,
        card_back: res.cardBack,
        checkAuth:res.is_auth
      })
    })
  },
  onShow() {
    setTimeout(() => { my.hideLoading() }, 500);
    let hasCreateSign = my.getStorageSync({ key: 'hasCreateSign' }).data;
    if (hasCreateSign) {
      const { code } = esignPlugin.getSignStatusInfo();
      if (code == '000') {
        my.showLoading({ content: '跳转中...' });
        setTimeout(() => { my.hideLoading() }, 1500);
        my.reLaunch({
          url: '/pagesA/pages/paySuccess/paySuccess?orderId=' + this.data.orderId
        })
      }
    }
  },
  onName(e) {
    this.setData({ userName: e.detail.value })
  },
  onIdcard(e) {
    this.setData({ userIdcard: e.detail.value })
  },
  uploadPhoto(e) {
    if(this.data.checkAuth=='1'){
      my.showToast({
        type: 'fail',
        content: '您已经完成实名认证,不可以再次修改证件照片！',
        duration: 2000,
      });
    }else{
      const that = this;
    let cardId = e.currentTarget.dataset.id
    let list = []
    if (cardId == 1) {
      uploadImg(function (url) {
        if (url) {
          list.push(url);
          that.setData({
            frontCard: list,
            card_front: list[0]
          })
        }
      });
    } else {
      uploadImg(function (url) {
        if (url) {
          list.push(url);
          that.setData({
            backCard: list,
            card_back: list[0]
          })
        }
      });
    }
    }
    
  },
  // e签宝
  isContract() {
    const that = this
    const { orderId, esignFlowId, esignUserId } = that.data
    const env = 'prod'
    if ((esignFlowId && esignFlowId != 0 && esignFlowId != 'null') && esignUserId) {
      my.setStorage({ key: 'hasCreateSign', data: true });
      my.showLoading({ content: '正在跳转合同...' });
      setTimeout(() => { my.hideLoading() }, 800);
      my.navigateTo({
        url: `plugin://esign/esign?env=${env}&flowId=${esignFlowId}&signerId=${esignUserId}`,
      })
    } else {
      my.showLoading({ content: '正在跳转合同...' });
      createContract(orderId).then(res => {
        if (res.flowId) {
          my.hideLoading({ page: that });
          my.setStorage({ key: 'hasCreateSign', data: true });
          const { flowId, signerId } = res
          my.navigateTo({
            url: `plugin://esign/esign?env=${env}&flowId=${flowId}&signerId=${signerId}`,
          })
        }
      })
    }
  },
  // 预授权
  // createAuth() {
  //   const that = this;
  //   const { orderId, payType } = that.data
  //   if (payType == 2 || payType==1) {
  //     createPreAuth(orderId).then(res => {
  //       if (res.orderStr) {
  //         my.tradePay({
  //           orderStr: res.orderStr,
  //           success: (res) => {
  //             if (res.resultCode == 9000) {
  //               my.reLaunch({ url: '../../packageB/pages/paySuccess/paySuccess?orderId=' + orderId })
  //             } else {
  //               if(payType == 2){
  //                 my.confirm({
  //                   title: '提示',
  //                   content: '押金过高？试试申请押金减免',
  //                   confirmButtonText: '是,申请',
  //                   cancelButtonText: '否',
  //                   success: res => {
  //                     if (res.confirm) {
  //                       my.redirectTo({ url: '../../packageA/pages/myOrder/myOrder?order_status='+0 })
  //                     } else {
  //                         my.reLaunch({ url: '../user/orderpay/orderpay?id=' + orderId })
  //                     }
  //                   },
  //                 });
  //               }
  //             }
  //           },
  //           fail: (res) => {
  //             my.showToast({
  //               type: 'fail',
  //               content: '支付失败，请稍后重试',
  //               duration: 1000,
  //             });
  //           }
  //         });
  //       } else {
  //         my.reLaunch({
  //           url: '../../packageB/pages/paySuccess/paySuccess?orderId=' + orderId
  //         })
  //       }
  //     })
  //   } else if (payType == 3) {
  //     createHuabei(orderId).then(res => {
  //       if (res.trade_no) {
  //         my.tradePay({
  //           tradeNO: res.trade_no,
  //           success: (res) => {
  //             let data = JSON.parse(JSON.stringify(res))
  //             if (data.resultCode == 9000) {
  //               my.reLaunch({
  //                 url: '../../packageB/pages/paySuccess/paySuccess?orderId=' + orderId
  //               })
  //             } else {
  //               my.showToast({
  //                 type: 'fail',
  //                 content: '支付失败，请稍后重试',
  //                 duration: 1000,
  //               });
  //             }
  //           }
  //         });
  //       } else {
  //         if (res.sign_status == 0) {
  //           that.isContract()
  //         } else if (res.sign_status == 1) {
  //           my.confirm({
  //             title: '提示',
  //             content: '继续签署合同?',
  //             confirmButtonText: '是,继续',
  //             cancelButtonText: '否,回首页',
  //             success: info => {
  //               if (info.confirm) {
  //                 my.showLoading({ content: '正在跳转合同...' });
  //                 setTimeout(() => { my.hideLoading() }, 800);
  //                 my.setStorage({ key: 'hasCreateSign', data: true });
  //                 my.navigateTo({
  //                   url: `plugin://esign/esign?env=${'prod'}&flowId=${res.flow_id}&signerId=${res.esign_user_id}`,
  //                 })
  //               } else {
  //                 my.switchTab({ url: '/pages/index/index' })
  //               }
  //             },
  //           });
  //         }else if(payType == 1){

  //         } else {
  //           my.showLoading({ content: '合同已签署完成...' });
  //           setTimeout(() => { my.hideLoading() }, 1000);
  //           my.switchTab({ url: '/pages/index/index' })
  //         }
  //       }
  //     })
  //   }
  // },
  toAuth() {
    const that = this
    const { userName, userIdcard, card_front, card_back, orderStatus, contractType, orderId, gooddsId } = that.data
    if (!userName || !userIdcard) {
      my.showToast({
        type: 'none',
        duration: 1500,
        content: '个人信息不能为空'
      });
      return
    } else if (!card_front || !card_back) {
      my.showToast({
        type: 'none',
        duration: 1500,
        content: '证件照不能为空'
      });
      return
    }
    if (userName && !checkName(userName)) {
      return;
    }
    if (userIdcard && !validateIdCard(userIdcard)) {
      return;
    }
    console.log(this.data.orderId);
    realPersonAuth({
      orderId:this.data.orderId,
      certName: userName,
      certNo: userIdcard,
      cardFront: card_front,
      cardBack: card_back,
      gooddsId,
      type:1
    }).then(res => {
      if (orderStatus == 3 || orderStatus == 9 || orderStatus == 10) {
        if (contractType == 1) {
        } else if (contractType == 2) {
        }
      } else {
        if (res.certify_id) {
          if(this.data.flag == "true"){
            my.startAPVerify({
              url: res.certify_url,
              certifyId: res.certify_id,
              success:function(info){
                checkPersonAuth(res.certify_id).then(result=>{
                  console.log(222);
                  my.reLaunch({
                    url: '/pagesA/pages/makeOrder/makeOrder?isauth=' + 1+ '&goodsIds=' + that.data.gooddsId + '&setmealId=' + that.data.setmealId
                          + '&leaseId=' + that.data.spectId + '&num=' + that.data.amount + '&activity_id=' + that.data.activityId+'&sale_user_id='+app.globalData.sale_user_id
                  })
                })
              }
            })
          }else{
            //刷脸
            my.startAPVerify({
              url: res.certify_url,
              certifyId: res.certify_id,
              success: function (info) {
                checkPersonAuth(res.certify_id).then(result=>{
                  if (info.resultStatus == 9000) {
                    if (contractType == 1) {
                    } else {
                      my.showLoading({
                        content: '加载中...',
                        complete:(res=>{
                          setTimeout(() => {
                            my.hideLoading();
                          }, 2000);
                        })
                      });
                      console.log(111);
                      my.reLaunch({
                        url: '/pagesA/pages/paySuccess/paySuccess?orderId=' + orderId
                      })
                      // that.createAuth()
                    }
                  }
                })
              }
            })
          }
        } else {
          if (contractType == 1) {
          } else {
            // that.createAuth()
          }
        }
      }
    })
  },
  submitBtn(){
    this.toAuth();
  }
});